package middleware

import (
	"fmt"
	"github.com/gin-gonic/gin"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jassue/jassue-gin/app/common/response"
	"github.com/jassue/jassue-gin/app/models"
	"github.com/jassue/jassue-gin/app/services"
	"github.com/jassue/jassue-gin/utils"
	"strconv"
	"strings"
)

func Auth() gin.HandlerFunc {
	return func(c *gin.Context) {

		// 获取用户id role_id   v0 的值
		// 找到 v1 的值
		obj := c.Request.URL.RequestURI()
		MenuId := services.MenuService.GetMenuId(obj)

		fmt.Printf("MenuId:%+v\n", MenuId)

		if MenuId == "" {
			response.AuthFail(c)
			c.Abort()
			return
		}

		// 获取用户的角色
		uid := c.Keys["id"].(string)
		intId, _ := strconv.Atoi(uid)
		_, role_ids := services.RoleService.GetUserRoles(intId)

		// 获取请求方法 strings.ToLower(c.Request.Method)
		act := strings.ToLower(c.Request.Method)

		fmt.Printf("role_ids:%+v\n", role_ids)
		fmt.Println(obj)
		fmt.Println(act)

		e := models.Casbin()

		if len(role_ids) != 0 {
			for _, v := range role_ids {

				fmt.Printf("intId:%+v\n", v.RoleId)

				flag, _ := e.Enforce(utils.Int2string(v.RoleId), MenuId, act)

				fmt.Println(flag)
				if flag {
					//通过
					return
				}
			}
		}

		response.AuthFail(c)
		c.Abort()
		return
	}
}
